package com.media.voice_rcd;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.media.MediaRecorder;
import android.os.Environment;

public  class SoundRecorder {
	public final static String ROOT_PATH = Environment.getExternalStorageDirectory() + "/family/";
	public final static String SOUND_CACHE_PATH = ROOT_PATH + "sound/";

	static final private double EMA_FILTER = 0.6;

	private MediaRecorder mRecorder = null;
	private double mEMA = 0.0;

	public void start(String fileName) {
		File file = new File(SOUND_CACHE_PATH);
		if(!file.exists()){
			file.mkdir();
		}
		
		if (fileName == null || fileName.equals("")) {
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			fileName = format.format(new Date(System.currentTimeMillis())) + ".amr";
		}
		
		
		if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return;
		}
		if (mRecorder == null) {
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			mRecorder.setOutputFile(SOUND_CACHE_PATH + fileName);
		}
		try {
			mRecorder.prepare();
			mRecorder.start();
			
			mEMA = 0.0;
		} catch (IllegalStateException e) {
			System.out.print(e.getMessage());
		} catch (IOException e) {
			System.out.print(e.getMessage());
		}
	}

	public void stop() {
		if (mRecorder != null) {
			mRecorder.stop();
			mRecorder.release();
			mRecorder = null;
		}
	}

	public void pause() {
		if (mRecorder != null) {
			mRecorder.stop();
		}
	}

	public void start() {
		if (mRecorder != null) {
			mRecorder.start();
		}
	}

	public double getAmplitude() {
		if (mRecorder != null)
			return (mRecorder.getMaxAmplitude() / 270.0);//2700
		else
			return 0;

	}

	public double getAmplitudeEMA() {
		double amp = getAmplitude();
		mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
		return mEMA;
	}

	public void delete(String name) {
		File file = new File(SOUND_CACHE_PATH + name);
		if (file.exists()) {
			file.delete();
		}
	}
	
	public String getCachePath(){
		return SOUND_CACHE_PATH;
	}
}
